using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using JetBrains.Annotations;

namespace Kaleida.ServiceMonitor.Model.Email
{
	internal class ScriptEmailSender
	{
		private readonly string scriptName;
		[CanBeNull]
		private string smtpServer;
		[CanBeNull]
		private MailAddress senderEmail;
		private readonly List<MailAddress> recipients;

		public ScriptEmailSender(string scriptName, IEnumerable<MailAddress> recipients)
		{
			this.scriptName = scriptName;
			this.recipients = recipients.ToList();
		}

		public void Configure(IConfiguration config)
		{
			if (string.IsNullOrWhiteSpace(config.SmtpServer))
				throw new InvalidOperationException(string.Format("SmtpServer is not set in the config. Cannot send emails from script '{0}'", scriptName));

			if (config.EmailSenderAddress == null)
				throw new InvalidOperationException(string.Format("EmailSenderAddress is not set in the config. Cannot send emails from script '{0}'", scriptName));

			Configure(config.SmtpServer, config.EmailSenderAddress);
		}

		public void Configure([NotNull] string smtp, [NotNull] MailAddress sender)
		{
			if (smtp == null) throw new ArgumentNullException("smtp");
			if (sender == null) throw new ArgumentNullException("sender");

			smtpServer = smtp;
			senderEmail = sender;
		}

		public void TrySendEmail(NotificationMessage notification)
		{
			if (senderEmail == null || smtpServer == null)
				throw new InvalidOperationException("Must first call Configure to set SmtpServer and EmailSenderAddress");

			if (recipients.Any())
			{
				using (var client = new SmtpClient(smtpServer))
				{
					var message = new MailMessage
					                  {
					                      Subject = notification.Subject,
                                          IsBodyHtml = true,
                                          Body = "Must be viewed using HTML-compatible email client"
					                  };
					foreach (var recipient in recipients)
					{
						message.To.Add(recipient);
					}
					message.From = senderEmail;

                    var htmlView = AlternateView.CreateAlternateViewFromString(notification.BodyHtml, null, "text/html");
                    message.AlternateViews.Add(htmlView);

					client.Send(message);
				}
			}
		}

	}
}